package com.dsg.controller.account;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dsg.aspect.NoRepeatSubmit;
import com.dsg.common.constants.MessageConstants;
import com.dsg.common.dto.AjaxResult;
import com.dsg.common.security.SystemAuthorizingUser;
import com.dsg.common.util.DateUtils;
import com.dsg.common.util.SingletonLoginUtils;
import com.dsg.common.util.toolbox.CollectionUtil;
import com.dsg.common.util.toolbox.StringUtil;
import com.dsg.controller.base.BaseController;
import com.dsg.entity.account.DsgAccountTrade;
import com.dsg.entity.model.account.DsgAccountTradeModel;
import com.dsg.service.account.IDsgAccountTradeService;
import com.dsg.util.EasyExcelUtils;
import com.dsg.util.easyExcel.ExcelMergeCellByColumnStrategy;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 交易帳目 前端控制器
 * </p>
 *
 * @author system
 * @since 2020-07-12
 */
@Slf4j
@RestController
@RequestMapping("/account/dsgAccountTrade")
@Api(description = "交易帳目")
public class DsgAccountTradeController extends BaseController {

    @Autowired
    private IDsgAccountTradeService dsgAccountTradeService;

    /**
     * 查詢列表（分頁）
     *
     * @param dsgAccountTrade
     * @return
     */
    @GetMapping(value = "/list")
    @ApiOperation("查詢列表（分頁）")
    public AjaxResult list(DsgAccountTrade dsgAccountTrade) {
        // 分页
        Page page = getPage();
        String sort = getParameter("sort");
        List<OrderItem> orderItemList = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        if (StringUtil.isEmpty(sort)) {
            orderItem.setColumn("A.CREATE_TIME desc,A.CARD_NO");
            orderItem.setAsc(false);
            orderItemList.add(orderItem);
            page.setOrders(orderItemList);
        }
        dsgAccountTrade.setEntCode(SingletonLoginUtils.getSystemEntCode());
        IPage<DsgAccountTrade> dsgAccountTradeIPage = dsgAccountTradeService.selectByList(page, dsgAccountTrade);
        // 格式要返回的数据
        AjaxResult ajaxResult = json(MessageConstants.SSO_STATUS_SUCCESS, dsgAccountTradeIPage.getRecords(), (int) page.getTotal());
        return ajaxResult;
    }

    /**
     * 新增
     *
     * @param dsgAccountTrade
     * @return
     */
    @NoRepeatSubmit
    @PutMapping(value = "/add")
    @ApiOperation("新增")
    public AjaxResult add(@RequestBody DsgAccountTrade dsgAccountTrade) {
        dsgAccountTradeService.saveDsgAccountTrade(dsgAccountTrade);
        return result(MessageConstants.SSO_STATUS_SUCCESS);
    }


    /**
     * 費用調整分頁查詢
     *
     * @param dsgAccountTrade
     * @return
     */
    @GetMapping(value = "/listAdj")
    @ApiOperation("費用調整分頁查詢")
    public AjaxResult listAdj(DsgAccountTrade dsgAccountTrade) {
        // 分页
        Page page = getPage();
        String sort = getParameter("sort");
        List<OrderItem> orderItemList = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        if (StringUtil.isEmpty(sort)) {
            orderItem.setColumn("a.CREATE_TIME");
            orderItem.setAsc(false);
            orderItemList.add(orderItem);
            page.setOrders(orderItemList);
        }
        dsgAccountTrade.setEntCode(SingletonLoginUtils.getSystemEntCode());
        IPage<DsgAccountTrade> dsgAccountTradeIPage = dsgAccountTradeService.selectListAdj(page, dsgAccountTrade);
        // 格式要返回的数据
        AjaxResult ajaxResult = json(MessageConstants.SSO_STATUS_SUCCESS, dsgAccountTradeIPage.getRecords(), (int) page.getTotal());
        return ajaxResult;
    }

    /**
     * 結單
     *
     * @return
     */
    @NoRepeatSubmit
    @PutMapping(value = "/statement")
    @ApiOperation("結單")
    public AjaxResult statement(@ApiParam(value = "油咭分類", name = "cardClassify", required = true) @RequestParam String cardClassify) {
        dsgAccountTradeService.statement(cardClassify);
        return result(MessageConstants.SSO_STATUS_SUCCESS);
    }

    /**
     * 查詢結單列表(分頁)
     *
     * @param beginDate    新增日期開始
     * @param endDate      新增日期結束
     * @param cardClassify 油咭分類 1:記賬咭 2:現金咭
     * @return
     */
    @GetMapping(value = "listStatement")
    @ApiOperation("查詢結單列表(分頁)")
    public AjaxResult listStatement(@ApiParam(value = "新增日期開始", name = "beginDate") @RequestParam String beginDate,
                                    @ApiParam(value = "新增日期結束", name = "endDate") @RequestParam String endDate,
                                    @ApiParam(value = "油咭分類 1:記賬咭 2:現金咭", name = "cardClassify", required = true) @RequestParam Integer cardClassify) {
        // 分页
        Page page = getPage();
        String sort = getParameter("sort");
        List<OrderItem> orderItemList = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        if (StringUtil.isEmpty(sort)) {
            orderItem.setColumn("a.SETTL_MONTH");
            orderItem.setAsc(false);
            orderItemList.add(orderItem);
            page.setOrders(orderItemList);
        }
        DsgAccountTrade dsgAccountTrade = new DsgAccountTrade();
        dsgAccountTrade.setBeginDate(beginDate);
        dsgAccountTrade.setEndDate(endDate);
        dsgAccountTrade.setEntCode(SingletonLoginUtils.getSystemEntCode());
        dsgAccountTrade.setCardClassify(cardClassify);
        IPage<DsgAccountTrade> dsgAccountTradeIPage = dsgAccountTradeService.selectStatementList(page, dsgAccountTrade);
        // 格式要返回的数据
        AjaxResult ajaxResult = json(MessageConstants.SSO_STATUS_SUCCESS, dsgAccountTradeIPage.getRecords(), (int) page.getTotal());
        return ajaxResult;
    }

    /**
     * 下載月結單
     *
     * @param settlMonth   結算月份
     * @param cardClassify 油咭分類 1:記賬咭 2:現金咭
     * @param response
     * @throws Exception
     */
    @GetMapping(value = "/downloadFile")
    @ApiOperation("下載月結單")
    public void downloadFile(@ApiParam(value = "結算月份", name = "settlMonth", required = true) @RequestParam String settlMonth,
                             @ApiParam(value = "油咭分類 1:記賬咭 2:現金咭", name = "cardClassify", required = true) @RequestParam Integer cardClassify,
                             HttpServletResponse response) throws Exception {
        SystemAuthorizingUser user = SingletonLoginUtils.getSystemUser();
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = "月結單_" + user.getInputCopName() + "_" + DateUtils.getStringDate() + ".xlsx";
        response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName, "utf-8"));
        OutputStream out = response.getOutputStream();
        Page<DsgAccountTrade> page = new Page<>();
        int currentPage = 0;
        page.setSize(EasyExcelUtils.PER_WRITE_ROW_COUNT);
        // 排序
        List<OrderItem> orderItemList = new ArrayList<>();
        page.setOrders(orderItemList);
        List<DsgAccountTrade> dsgAccountTradeList;
        DsgAccountTrade dsgAccountTrade = new DsgAccountTrade();
        dsgAccountTrade.setEntCode(user.getOrgCode());
        dsgAccountTrade.setCardClassify(cardClassify);
        dsgAccountTrade.setSettlMonth(settlMonth);
        List<DsgAccountTradeModel> dsgAccountTradeModelList = new ArrayList<>();
        //需要合并的列
        int[] mergeColumnIndex = {0, 1, 2, 3, 4, 5, 6};
        //需要从第一行开始，列头第一行
        int mergeRowIndex = 1;
        // 设置第0列为标杆列
        int standardColumnIndex = 0;
        do {
            page.setCurrent(++currentPage);
            dsgAccountTradeList = dsgAccountTradeService.selectStatement(page, dsgAccountTrade).getRecords();
            if (CollectionUtil.isNotEmpty(dsgAccountTradeList)) {
                dsgAccountTradeList.forEach(I -> {
                    DsgAccountTradeModel dsgAccountTradeModel = new DsgAccountTradeModel();
                    BeanUtils.copyProperties(I, dsgAccountTradeModel);
                    dsgAccountTradeModelList.add(dsgAccountTradeModel);
                });
                EasyExcel.write(out, DsgAccountTradeModel.class).sheet("月結單")
                        .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                        .registerWriteHandler(new ExcelMergeCellByColumnStrategy(mergeRowIndex, mergeColumnIndex, standardColumnIndex))
                        .doWrite(dsgAccountTradeModelList);
            }
        } while (CollectionUtil.isNotEmpty(dsgAccountTradeList) && dsgAccountTradeList.size() == EasyExcelUtils.PER_WRITE_ROW_COUNT);
        out.flush();
    }
}
